package community.controller;

import community.mapper.UserMapper;
import community.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


@Controller //该注解表示允许这个类接收前端的请求
public class IndexController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/")
    public String index(HttpServletRequest servletRequest){
        //通过token返回user信息，如果存在，则直接登录，如果不存在则让用户登录
        Cookie[] cookies = servletRequest.getCookies();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("token")){
                String token = cookie.getValue();
                User user =userMapper.findByToken(token);  //驱动编程：先定义好返回值和方法名，再声明该方法
                if(user!=null){
                    servletRequest.getSession().setAttribute("user",user);
                }
                break;
            }
        }
        return "index";
    }
}